<template>
  <div class="tea-details h-100% w-100%">
    <swiper v-if="bannerList" autoplay circular class="h-460rpx" :style="{ paddingTop: `${searchBarTop}px` }">
      <swiper-item v-for="swip in bannerList" class="overflow-hidden">
        <image
          :src="swip"
          class="pointer-events-none h-460rpx w-full"
          mode="scaleToFill"
        />
      </swiper-item>
    </swiper>
    <!-- <image
      :src="`${cdnUrl}/imgs/teaDetailsPng/bg.png${imgVersion}`"
      class="pointer-events-none h-460rpx w-100%"
      mode="widthFix"
    /> -->
    <div class="content pl-32rpx pr-32rpx pt-44rpx">
      <div class="title mb-32rpx rounded-32rpx">
        <div v-if="goodsDetail" class="mb-32rpx flex items-center">
          <span class="text-32rpx font-600">{{ goodsDetail.productName }}</span>
          <image
            :src="`${cdnUrl}/svgicons/teaDetails/leaf.svg${imgVersion}`"
            mode="scaleToFill"
            class="h-48rpx w-48rpx"
          />
        </div>
        <!-- 必选 -->
        <div class="tag">
          <div v-for="(item, index) in tagList" class="mb-34rpx">
            <div class="mb-15rpx w-20% text-30rpx font-bold text-hex-333">{{ item.name }}</div>
            <div class="flex flex-wrap items-center">
              <div
                v-for="(tag, i) in item.childList"
                :class="item.val.name===tag.name?'text-hex-ABCD03 border-2rpx border-hex-ABCD03 border-solid':'text-hex-999'"
                class="mb-20rpx mr-24rpx h-44rpx rounded-8rpx bg-hex-f5f5f5 px-24rpx text-24rpx leading-44rpx"
                @click="selectType(item.necessaryFlag, item.id, tag, index)">
                {{ tag.name }}
              </div>
            </div>
          </div>
          <!-- 可选 -->
          <div
            v-if="optionalList?.length>0"
            class="mb-34rpx flex items-center">
            <span class="mr-56rpx text-24rpx text-hex-333">小料</span>
            <div
              v-for="(item, index) in optionalList"
              :class="index===0?'text-hex-ABCD03 border-2rpx border-hex-ABCD03 border-solid':'text-hex-999'"
              class="mr-24rpx h-44rpx rounded-8rpx bg-hex-f5f5f5 px-24rpx text-24rpx leading-44rpx"
            >
              {{ item.productSkuName }}
            </div>
          </div>
        </div>
      </div>
      <div class="relative mt-52rpx">
        <div class="hot relative box-border rounded-20rpx bg-hex-fff p-24rpx">
          <span class="title text-28rpx">
            <image
              :src="`${cdnUrl}/svgicons/search/emoji.svg${imgVersion}`"
              mode="scaleToFill"
              class="h-28rpx w-28rpx"
            />
            <span class="z-99">夏日推荐榜</span>
          </span>
          <div
            v-for="item in items"
            class="hot-item z-999 mt-36rpx h-180rpx flex pr-25rpx"
            @click="goDetail(item.unionFlag, item.id)">
            <div 
              class="relative mr-3% mt-24rpx h-180rpx w-180rpx overflow-hidden rounded-16rpx">
              <image
                class="absolute left-50% top-50% h-180rpx w-180rpx rounded-16rpx"
                style="transform: translate(-50%, -50%);" :src="item.productImage" mode="aspectFill" />
            </div>
            <div class="relative ml-20rpx h-100% flex-1">
              <div>
                <div class="text-28rpx font-600 leading-38rpx">{{ item.productName }}</div>
                <div class="mt-16rpx flex items-center text-24rpx text-hex-7C8699">
                  <!-- <div
                    v-for="itm in item.tagList"
                    class="tagClass relative mr-20rpx">{{ itm }}</div> -->
                  <!-- <div class="mx-10rpx h-14rpx w-2rpx rounded-22rpx bg-hex-7C8699" />
                  <div>养生饮</div>
                  <div class="mx-10rpx h-14rpx w-2rpx rounded-22rpx bg-hex-7C8699" />
                  <div>可去冰</div> -->
                  <div>{{ item.productIntro }}</div>
                </div>
              </div>
              <div class="absolute bottom-0 w-100%">
                <div class="flex items-center">
                  <div class="flex-1 text-28rpx text-hex-333">￥{{ item.productPrice }}</div>
                  <image
                    :src="`${cdnUrl}/svgicons/userComment/add.svg${imgVersion}`"
                    mode="scaleToFill"
                    class="mt-5rpx h-50rpx w-50rpx"
                  />
                </div>
              </div>
            </div>
          </div>
          <div
            v-if="moreShow"
            class="bgblur absolute bottom-0 left-0 right-0 h-100rpx w-100% flex items-center justify-center rounded-b-24rpx bg-[rgba(255,255,255,0.67)]"
            @click="getAllRecommentList">
            <image
              :src="`${cdnUrl}/imgs/tea/downMore.png${imgVersion}`"
              mode="scaleToFill"
              class="h-32rpx w-32rpx"
            />
            <span class="text-24rpx text-hex-7C8699">展开全部</span>
          </div>
        </div>
      </div>
      <div
        class="mt-32rpx h-98rpx flex items-center justify-between rounded-12rpx bg-hex-fff px-32rpx leading-98rpx"
        @click="navTo(`/pages-tea/userComment?productId=${productId}`)">
        <span class="text-24rpx text-hex-262626">用户评价({{ evaluationNumber }})</span>
        <image
          :src="`${cdnUrl}/imgs/tea/more.png${imgVersion}`"
          mode="scaleToFill"
          class="h-30rpx w-30rpx"
        />
      </div>
      <div class="mt-32rpx box-border rounded-24rpx bg-hex-fff px-32rpx">
        <text class="font-28rpx my-32rpx inline-block text-24rpx font-600 text-hex-000">商品详情</text>
        <div v-if="goodsDetailContent" class="mb-32rpx">
          <!-- <image
            v-for="item in goodsDetailContent"
            :src="item"
            class="w-100% rounded-24rpx"
            mode="widthFix"
          />
          <div
            v-if="goodsDetail"
            class="font-28rpx my-32rpx inline-block text-24rpx font-600 text-hex-000">{{ goodsDetail.productIntro }}</div> -->
          <rich-text :nodes="goodsDetailContent" />
        </div>

      </div>
      <div class="h-220rpx" />
    </div>
    <div class="absolute top-0 w-100%" :style="{ paddingTop: `${topHight}px` }">
      <uni-nav-bar left-icon="left" :border="false" background-color="transparent" color="#ABCD03" @clickLeft="goback" />

      <!-- 收藏按钮 -->
      <div class="absolute right-62rpx top-620rpx">
        <div
          class="h-92rpx w-92rpx flex items-center justify-center border-2rpx border-hex-fff rounded-100% border-solid bg-hex-f5f5f5"
          @click="handelCollect">
          <image
            :src="`${cdnUrl}/svgicons/pl_save${isCollect}.svg${imgVersion}`"
            mode="scaleToFill"
            class="h-56rpx w-56rpx"
          />
        </div>
        <div class="mt-16rpx text-center text-24rpx text-hex-7c8699">{{ isCollect?'已收藏':'收藏' }}</div>
      </div>
    </div>
    <div class="fixed bottom-0 left-0 right-0 z-99 box-border rounded-t-32rpx bg-hex-fff p-32rpx pb-50rpx">
      <div class="mb-16rpx flex items-center justify-between">
        <div>
          <div class="mb-10rpx">
            <text class="font-numberFont mr-10rpx text-28rpx text-hex-E36043">￥{{ finallPrice }}</text>
            <text class="text-24rpx text-hex-999" style="text-decoration: line-through;">￥{{ goodsDetail.cost }}</text>
          </div>
          <div class="text-24rpx text-hex-7C8699">{{ selectName }}</div>
        </div>
        <div class="flex items-center">
          <image
            :src="`${cdnUrl}/svgicons/userComment/down.svg${imgVersion}`"
            mode="scaleToFill"
            class="mt-5rpx h-50rpx w-50rpx"
            @click="reduceShop"
          />
          <div class="ml-24rpx mr-24rpx">{{ shopnum }}</div>
          <image
            :src="`${cdnUrl}/svgicons/userComment/add.svg${imgVersion}`"
            mode="scaleToFill"
            class="mt-5rpx h-50rpx w-50rpx"
            @click="addShop"
          />
        </div>
      </div>
      <div class="flex justify-between text-28rpx">
        <!-- <div class="h-72rpx w-328rpx border-2rpx border-hex-ABCD03 rounded-46rpx border-solid text-center leading-72rpx text-hex-ABCD03" @click="navTo('/pages-tea/comfirmOrder')">立即购买</div> -->
        <div class="btn-theme-bg h-72rpx w-100% rounded-46rpx text-center leading-72rpx text-hex-fff" @click="joinGoodsCar">加入购物车</div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { useUserStore } from '@/stores/user'
import { useAddressStore } from '@/stores/address'

import { useLoginStore } from '@/stores/login'

const loginStore = useLoginStore()
let addressStores: any = useAddressStore()

const userStores = useUserStore()
let topHight = $ref(0)
let productId: any = $ref('')
let searchBarTop: any = $ref('24')
onLoad((options) => {
  let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
  searchBarTop = menuButtonInfo.top + 35
  // #ifdef MP-WEIXIN
  const { capsuleTop } = useCapsulePosition()
  topHight = capsuleTop.value
  // #endif
  if (options) {
    productId = options.productId
  }
})

let items: any = $ref([]) //套餐列表
let tagList: any = $ref([]) //必有标签列表 杯型，温度，糖分
let initList: any = $ref([])
let finallPriceSelectList: any = $ref([])

let finallPrice: any = $ref(0)
let filterskuList: any = $ref([]) //最后选择的skuList
const selectType = (type, id, item, index) => {
  let tempNameList: any = []
  selectName = tempNameList[0] = initGoodsName
  tagList[index].val = item
  initList = []
  tagList.forEach((item: any) => {
    initList.push({
      'attributeId': item.id,
      'attributeValueIds': [item.val.id],
    })
    tempNameList.push(item.val.name)
  })
  selectName = tempNameList.join('+')
  if (type === 1) {
    let tempIndex: any = 0
    tempIndex = finallPriceSelectList.findIndex((itm) => {
      return itm.kid === id
    })
    finallPriceSelectList[tempIndex].childList[0] = item
  }
  filterskuList = skuList.filter((skuitem) => {
    return skuitem.specs[0].v_id === finallPriceSelectList[0].childList[0].id
  })
  finallPrice = filterskuList[0].productSkuPrice
}
// 加入购物车
const joinGoodsCar = async () => {
  const reqData = {
    method: 'post',
    data: {
      'detailDTO': {
        'amount': shopnum,
        'childrenSkus': [
          {
            'attributes': initList,
            'productId': nessOptionsList[0].childProductId,
            'skuId': filterskuList[0].id,
          },
        ],
        'isJoinedActivity': false,
        'productId': productId,
      },
      'trolleyType': 2,
      'userId': userStores.user.id,
    },
    headers: { UserId: userStores.user.id },
  }
  uni.showLoading({ title: '加入中' })
  const { data, status, error } = await Fetch('/qqyapi/order/trolley/addItem', reqData)
  if (status !== 200 || data.code !== 0) {
    uni.hideLoading()
    return
  }
  if (data.code === 0) {
    uni.hideLoading()
    uni.showToast({
      title: '商品已加入购物车',
      icon: 'none',
    })
    setTimeout(() => {
      uni.switchTab({ url: '/pages/index' })
      uni.$emit('handelEvent')
    }, 600)
  }

}

const goDetail = (type, id) => {
  if (type === 1) {
    navTo(`/pages-tea/doubleDetails?productId=${id}`)
  } else {
    navTo(`/pages-tea/details?productId=${id}`)
  }
}

//商品数量
let shopnum = $ref(1)
//商品减
const reduceShop = () => {
  if (shopnum > 1) {
    shopnum = shopnum - 1
  }
}
//商品添加
const addShop = () => {
  if (shopnum < 20) {
    shopnum = shopnum + 1
    return
  }
  uni.showToast({
    title: '超过最大加购数量',
    icon: 'none',
  })
}

let goodsDetail: any = $ref({}) //商品详情
let goodsDetailContent: any = $ref([])
let recommendList: any = $ref([])
let moreShow: any = $ref(false)
let optionalList: any = $ref([]) //可选（小料）
let nessOptionsList: any = $ref([]) //必选
let skuList: any = $ref([])
let bannerList: any = $ref([]) //轮播图
let selectName: any = $ref('')
let initGoodsName: any = $ref('')
// 获取商品详情
const getGoodsDetail = async () => {
  const reqData = {
    method: 'post',
    data: {
      'productId': productId,
      'storeId': addressStores.selectStores.id,
      appType: 2,
    },
    headers: {
      AppType: 2,
      UserId: userStores.user.id,
    },
  }
  const { data, status, error } = await Fetch('/qqyapi/product/product/detail', reqData)
  if (status !== 200 || data.code !== 0) {
    return
  }
  let tempList = data.result.productElementList
  goodsDetail = data.result
  bannerList = goodsDetail?.productBannerImage.split(',')
  finallPrice = goodsDetail.productPrice
  initGoodsName = goodsDetail.productName
  // 必选
  nessOptionsList = tempList.filter((item) => {
    return item.optionFlag === 1
  })
  tagList = nessOptionsList[0]?.attributeList
  skuList = nessOptionsList[0]?.skuList


  // 可选
  let canOptionsList: any = []
  canOptionsList = tempList.filter((item) => {
    return item.optionFlag === 0
  })
  canOptionsList.forEach((item) => {
    optionalList.push(item.skuList[0])
  })

  skuList.forEach((item) => {
    item.specs = JSON.parse(item.specs)
  })
  let tempNameList: any = []
  selectName = tempNameList[0] = initGoodsName
  tagList.forEach((item: any) => {
    item.val = item.childList[0]
    tempNameList.push(item.val.name)
    initList.push({
      'attributeId': item.id,
      'attributeValueIds': [item.val.id],
    })
    if (item.necessaryFlag === 1) {
      let tempOption: any = {}
      tempOption.kid = item.id
      tempOption.childList = []
      tempOption.childList.push(item.childList[0])
      finallPriceSelectList.push(tempOption)
    }
  })


  selectName = tempNameList.join('+') //最终选择商品的简介
  skuList.forEach((skuitem) => {
    if (skuList.length === 1) {
      finallPrice = skuitem.productSkuPrice
      return
    }
    if (skuitem.specs) {
      if (skuitem.specs[0].v_id === finallPriceSelectList[0].childList[0].id) {
        finallPrice = skuitem.productSkuPrice
      }
    }
  })
  if (skuList.length === 1) {
    filterskuList = skuList
  } else {
    filterskuList = skuList.filter((skuitem) => {
      return skuitem.specs[0].v_id === finallPriceSelectList[0].childList[0].id
    })
  }
  // console.log(filterskuList, 'filterskuList')
  // console.log(tagList, 'tagList')
  // console.log(initList, 'initList')
  // goodsDetailContent = goodsDetail?.productDetailImage.split(',')
  goodsDetailContent = goodsDetail?.productDetailImage.replace(/style=""/g, 'style="max-width:100% !important;display:block;"')
  recommendList = goodsDetail?.recommendList
  if (recommendList && recommendList.length > 3) {
    items = recommendList.splice(0, 3)
    moreShow = true
    return
  }
  items = recommendList
}

const getAllRecommentList = () => {
  items = recommendList
  moreShow = false
}

let isCollect: any = $ref(false)
// 查询用户是否收藏该商品
const getIsCollect = async () => {
  const reqData = {
    method: 'post',
    data: {
      'productId': productId,
    },
    headers: {
      AppType: 2,
      UserId: userStores.user.id,
    },
  }
  const { data, status, error } = await Fetch('/qqyapi/product/product/collect/isCollect', reqData)
  if (status !== 200 || data.code !== 0) {
    return
  }
  isCollect = data.result
}

// 收藏,取消收藏商品
const handelCollect = useThrottleFn(async () => {
  if (!loginStore.roleId) {
    loginStore.setIsBack(true)
    loginStore.isGoLogin()
    return
  }
  const reqData = {
    method: 'post',
    data: {
      'productId': productId,
    },
    headers: {
      AppType: 2,
      UserId: userStores.user.id,
    },
  }
  const url = isCollect ? '/qqyapi/product/product/collect/delete' : '/qqyapi/product/product/collect/add'
  const { data, status, error } = await Fetch(url, reqData)
  if (status !== 200 || data.code !== 0) {
    return
  }
  getIsCollect()
}, 500)

let evaluationNumber: any = $ref(0)
// 查看商品评价数量
const getGoodsEvaluationNum = async () => {
  const reqData = {
    method: 'post',
    data: {
      'productId': productId,
    },
    headers: {
      AppType: 2,
      userId: userStores.user.id,
    },
  }
  const { data, status, error } = await Fetch('/qqyapi/product/product/evaluation/countByProductId', reqData)
  if (status !== 200 || data.code !== 0) {
    return
  }
  evaluationNumber = data.result
}


onMounted(() => {
  getIsCollect()
  getGoodsDetail()
  getGoodsEvaluationNum()
})

//返回上一级
const goback = () => {
  uni.navigateBack({
    delta: 1,
  })
}
</script>

<style lang="scss">
.tea-details{
  background: linear-gradient(180deg, #FFF 0%, #f5f5f5 100%);

  .activeClass{
    background-color: #EDFDF8;
    border: 1rpx solid #ABCD03 ;
  }

  .hot{
    background: #fff;
    background-size: 100%;
    background-repeat: no-repeat;
  }

  .bgblur{
    backdrop-filter: blur(8rpx);
  }

  // ::v-deep .uni-icons{
  //   color: #18a786 !important;
  // }

  .font-numberFont{
    font-family:'DingTalk JinBuTi';
  }

  .scroll-view-item {
    height: 300rpx;
  }

  .scrolldemo{
    scrollbar-width: none; /* firefox */
    -ms-overflow-style: none; /* IE 10+ */
    overflow-x: hidden;
  }

  ::-webkit-scrollbar {
    display: none; /* Chrome Safari */
  }

  .tagClass::after{
    position: absolute;
    content: '';
    height:14rpx;
    width:2rpx;
    top: 10rpx;
    right: -10rpx;
    background-color: #7c8699;
  }

  .tagClass:last-child::after{
    width: 0rpx;
    height:0rpx;
  }
}

</style>
